package com.lebang.medicalInquiry.component;

import com.google.gson.Gson;


import com.lebang.medicalInquiry.exception.BusinessException;
import com.lebang.medicalInquiry.model.vo.UserTokenVo;
import com.lebang.medicalInquiry.utils.AESUtil;
import com.lebang.medicalInquiry.utils.TextUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 * @program: LazyAssistant
 * @description: 生成用户访问的token
 * @author: tony
 * @create: 2019-11-26 16:09
 **/
@Component
public class TokenComponent {


    @Value("${aes.secret}")
    private String secret;


    /**
     * 生成用户的token
     *
     * @param userTokenVo
     * @return
     */
    public String getToken(UserTokenVo userTokenVo) {
        try {
            if (userTokenVo != null) {

                return AESUtil.encryptHex(userTokenVo.toString(), secret);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public UserTokenVo getMember(String token) {

        if (!TextUtil.isEmpty(token)) {
            String data = AESUtil.decryptHex(token, secret);
            if (TextUtil.isEmpty(data)) {
                System.out.println("错误token：" + token);
                throw new BusinessException("token异常");
            }
            return new Gson().fromJson(data, UserTokenVo.class);
        }

        return null;
    }


    /**
     * 直接根据请求获取用户信息
     *
     * @param request
     * @return
     */
    public UserTokenVo getMember(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (!TextUtil.isEmpty(token)) {
                String data = AESUtil.decryptHex(token, secret);
                return new Gson().fromJson(data, UserTokenVo.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
